package cn.sibu.myroot.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

/**
 * Created by 刘红亮 on 15-12-18 下午1:57.
 */
public class PerspectiveScrollContenView extends LinearLayout {

    //每个子视图的缩放比例都是可调节的

    private static final float SCALE_FACTOR = 0.7f;

    //变换的轴心点.(0,0)是左上,(1,1)是右下. 当前设置的是底部中间(0.5,1)
    private static final float ANCHOR_X = 0.5f;
    private static final float ANCHOR_Y = 1.0f;

    public PerspectiveScrollContenView(Context context) {
        super(context);
        init();
    }

    public PerspectiveScrollContenView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PerspectiveScrollContenView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        //启动静态变换,这样对于每个子视图,getChildStaticTransformation()
        //都会被调用
        setStaticTransformationsEnabled(true);
    }

    //工具方法,用于计算屏幕坐标系内所有视图的当前位置
    private int getViewCenter(View view){
        int[] childCoords = new int[2];
        Log.e("childCoords","childCoords[0]== "+childCoords[0]+"  childCoords[1]=="+childCoords[1]);
        view.getLocationOnScreen(childCoords);
        int childCenter = childCoords[0]+(view.getWidth()/2);
        return childCenter;
    }

    @Override
    protected boolean getChildStaticTransformation(View child, Transformation t) {
        Log.e("StaticTransformation","StaticTransformation");
        HorizontalScrollView scrollView = null;
        if(getParent() instanceof HorizontalScrollView){
            scrollView = (HorizontalScrollView) getParent();
        }
        if(scrollView == null){
            return false;
        }
        int childCenter = getViewCenter(child);
        int viewCenter = getViewCenter(scrollView);

        //计算子视图和父容器中心之间的距离,这会决定应用的缩放比例
        float delta  = Math.min(1.0f,Math.abs(childCenter-viewCenter)/(float)viewCenter);
        //设置最小的缩放比例为0.4
        float scale = Math.max(0.4f,1.0f-(SCALE_FACTOR*delta));
        float xTrans = child.getWidth()*ANCHOR_X;
        float yTrans = child.getHeight()*ANCHOR_Y;

        //清除现有的所有变换
        t.clear();
        //为子视图设置变换
        Log.e("scale","scale = "+scale);
        t.getMatrix().setScale(scale, scale, child.getWidth()/2,child.getHeight()/2);
        child.setAlpha(delta);
        return true;
    }
}
